package com.disruptor.sample._01base.run;

import com.disruptor.sample.common.dto.LongEvent;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import java.nio.ByteBuffer;
import lombok.extern.slf4j.Slf4j;

/**
 * 优化重写
 */
@Slf4j
public class LongEventMainByLambda {

  public static void handleEvent(LongEvent event, long sequence, boolean endOfBatch) {
    log.info("Event: " + event);
  }

  public static void translate(LongEvent event, long sequence, ByteBuffer buffer) {
    event.setValue(buffer.getLong(0));
  }

  public static void main(String[] args) throws Exception {
    int bufferSize = 1024;

    Disruptor<LongEvent> disruptor =
        new Disruptor<>(LongEvent::new, bufferSize, DaemonThreadFactory.INSTANCE);

    disruptor.handleEventsWith(LongEventMainByLambda::handleEvent);
    disruptor.start();

    RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
    ByteBuffer byteBuffer = ByteBuffer.allocate(8);
    for (long value = 0; true; value++) {
      byteBuffer.putLong(0, value);
      ringBuffer.publishEvent(LongEventMainByLambda::translate, byteBuffer);
      Thread.sleep(1000);
    }
  }
}
